<template>
  <div class="page-wrapper">
    <div class="page-header">
      <span class="text-primary font-bold">租户管理</span>
      <el-button type="primary" @click="handleAdd">新增租户</el-button>
    </div>

    <div class="page-content">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="租户名称">
          <el-input v-model="searchForm.name" placeholder="请输入租户名称" clearable />
        </el-form-item>
        <el-form-item label="租户AppID">
          <el-input v-model="searchForm.appId" placeholder="请输入租户AppID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table :data="tableData" v-loading="loading">
          <el-table-column prop="name" label="租户名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="appId" label="租户AppID" min-width="120" show-overflow-tooltip />
          <el-table-column
            prop="adminUsername"
            label="管理员账号"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              <el-button type="warning" link @click="handleResetPassword(row)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增租户' : '编辑租户'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="租户AppID" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入租户AppID" />
        </el-form-item>
        <el-form-item label="AppSecret" prop="appSecret">
          <el-input v-model="form.appSecret" placeholder="请输入AppSecret">
            <template #append>
              <el-button @click="handleGenerateSecret">生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="管理员账号" prop="adminUsername">
          <el-input v-model="form.adminUsername" placeholder="请输入管理员账号" />
        </el-form-item>
        <el-form-item label="管理员密码" prop="adminPassword" :required="dialogType === 'add'">
          <el-input
            v-model="form.adminPassword"
            type="password"
            placeholder="请输入管理员密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit"> 确定 </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置管理员密码" v-model="resetPwdVisible" width="400px" destroy-on-close>
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPwdForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPwdForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPwdVisible = false">取消</el-button>
        <el-button type="primary" :loading="resetPwdLoading" @click="handleResetPwdSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listTenant,
  addTenant,
  updateTenant,
  deleteTenant,
  generateSecret,
  resetPassword,
} from '@/api/system/tenant'
import type { TenantVo, TenantForm } from '@/types/system/tenant'

// 搜索表单
const searchForm = reactive({
  name: '',
  appId: '',
  status: undefined as undefined | number,
})

// 表格数据
const tableData = ref<TenantVo[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await listTenant({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取租户列表失败:', error)
    ElMessage.error('获取租户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.appId = ''
  searchForm.status = undefined
  handleSearch()
}

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = reactive({
  id: '',
  name: '',
  appId: '',
  appSecret: '',
  adminUsername: '',
  adminPassword: '',
  status: 1,
})

const rules = {
  name: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
  appId: [{ required: true, message: '请输入租户AppID', trigger: 'blur' }],
  appSecret: [{ required: true, message: '请输入AppSecret', trigger: 'blur' }],
  adminUsername: [{ required: true, message: '请输入管理员账号', trigger: 'blur' }],
  adminPassword: [{ required: true, message: '请输入管理员密码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 新增租户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  form.id = ''
  form.name = ''
  form.appId = ''
  form.appSecret = ''
  form.adminUsername = ''
  form.adminPassword = ''
  form.status = 1
}

// 编辑租户
const handleEdit = (row: TenantVo) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 删除租户
const handleDelete = async (row: TenantVo) => {
  try {
    await ElMessageBox.confirm('确认删除该租户吗？', '提示', {
      type: 'warning',
    })
    await deleteTenant(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 自动生成AppSecret
const handleGenerateSecret = async () => {
  try {
    const res = await generateSecret()
    form.appSecret = res.data
  } catch (error) {
    console.error('生成AppSecret失败:', error)
    ElMessage.error('生成AppSecret失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addTenant(form)
        } else {
          await updateTenant(form)
        }
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 重置密码相关
const resetPwdVisible = ref(false)
const resetPwdLoading = ref(false)
const resetPwdFormRef = ref<FormInstance>()
const currentTenantId = ref('')

const resetPwdForm = reactive({
  password: '',
  confirmPassword: '',
})

const resetPwdRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== resetPwdForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

// 打开重置密码对话框
const handleResetPassword = (row: TenantVo) => {
  resetPwdVisible.value = true
  currentTenantId.value = row.id
  resetPwdForm.password = ''
  resetPwdForm.confirmPassword = ''
}

// 提交重置密码
const handleResetPwdSubmit = async () => {
  if (!resetPwdFormRef.value) return
  await resetPwdFormRef.value.validate(async (valid) => {
    if (valid) {
      resetPwdLoading.value = true
      try {
        await resetPassword(currentTenantId.value, resetPwdForm.password)
        ElMessage.success('重置密码成功')
        resetPwdVisible.value = false
      } catch (error: any) {
        ElMessage.error(error.message || '重置密码失败')
      } finally {
        resetPwdLoading.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  loadData()
})
</script>
